﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using MinistryStandardPlatformWeb.Models.ReportCenter;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("44")]
    public class InOutRegionController : Controller
    {
        //
        // GET: /InOutRegion/
        private MSPDataContext context = new MSPDataContext();

        public ActionResult Index()
        {
            return View();
        }
        //[HttpPost]
        //public ActionResult GetData(string startTime, string endTime, List<string> vehicleNums, string regionType)
        //{
        //    if (!string.IsNullOrEmpty(startTime) && !string.IsNullOrEmpty(endTime) && vehicleNums != null && vehicleNums.Count != 0)
        //    {
        //        List<InOutRegion> retList = new List<InOutRegion>();
        //        List<TransDetail> list = (from t in this.context.TranTaskListDetail
        //                                  join r in this.context.TranTaskList
        //                                  on t.tranTaskListId equals r.taskListId
        //                                  where vehicleNums.Contains(t.vehicleNum)
        //                                  && r.insertTime.CompareTo(startTime) >= 0 && r.insertTime.CompareTo(endTime) <= 0
        //                                  select new TransDetail()
        //                                  {
        //                                      mVehicleNum = t.vehicleNum,
        //                                      mStationName = r.startRegName,
        //                                      mSiteName = r.endRegName,
        //                                      mLeaveStationTime = t.outStartRegTime,
        //                                      mArriveSiteTime = t.inEndRegTime,
        //                                      mLeaveSiteTime = t.outEndRegTime,
        //                                      mRetStationTime = t.inStartRegTime
        //                                  }).ToList();
        //        for (int i = 0; i < list.Count; i++)
        //        {
        //            TransDetail item = list[i];
        //            InOutRegion tmp;
        //            if (regionType.Equals("0") || regionType.Equals("1"))
        //            {
        //                tmp = new InOutRegion();
        //                tmp.mNum = item.mVehicleNum;
        //                tmp.mInTime = item.mRetStationTime;
        //                tmp.mOutTime = item.mLeaveStationTime;
        //                tmp.mRegionName = item.mStationName;
        //                tmp.mRegionType = "进出站点";
        //                retList.Add(tmp);
        //            }
        //            if (regionType.Equals("0") || regionType.Equals("2"))
        //            {
        //                tmp = new InOutRegion();
        //                tmp.mNum = item.mVehicleNum;
        //                tmp.mInTime = item.mArriveSiteTime;
        //                tmp.mOutTime = item.mLeaveSiteTime;
        //                tmp.mRegionName = item.mSiteName;
        //                tmp.mRegionType = "进出工地";
        //                retList.Add(tmp);
        //            }
        //        }
        //        var json = new
        //        {
        //            total = retList.Count,
        //            rows = retList
        //        };
        //        var serializer = new JavaScriptSerializer();
        //        serializer.MaxJsonLength = Int32.MaxValue;
        //        return Content(serializer.Serialize(json), "application/json");
        //    }
        //    return null;
        //}

        [HttpPost]
        public ActionResult GetData(string startTime, string endTime, List<string> sims)
        {
            if (!string.IsNullOrEmpty(startTime) && !string.IsNullOrEmpty(endTime) && sims != null && sims.Count != 0)
            {
                string sql = "select simid mSim,"
                + "warntype mType,"
                + "warnstarttime mInTime "
                + "from gpswarn "
                + "where (warntype='43' or warntype='14') and warnstarttime >= '" + startTime + "' and warnstarttime <= '" + endTime + "' and ";
                for (int i = 0; i < sims.Count; i++)
                {
                    if (i == 0)
                    {
                        sql += "(";
                    }
                    sql += "simid='" + sims[i] + "' or ";
                    if (i == sims.Count - 1)
                    {
                        sql += "1=0) ";
                    }
                }
                string historyStr = RealTimeGet.getReportFromGeoBase(
                    CommonFunctions.GetLoginUser().UserId,
                    sql,
                    startTime,
                    endTime,
                    "0");
                List<InOutRegion> modelList = new List<InOutRegion>();
                if (historyStr != "error" && historyStr != "")
                {
                    try
                    {
                        modelList = CommonFunctions.JsonStrToObject<List<InOutRegion>>(historyStr);
                        for (int i = 0; i < modelList.Count; i++)
                        {
                            InOutRegion model = modelList[i];
                            if (model.mType.Equals("43"))
                            {//出区域
                                model.mOutTime = model.mInTime;
                                model.mInTime = "";
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        return null;
                    }
                }
                else
                {
                }
                var json = new
                {
                    total = modelList.Count,
                    rows = (from r in modelList
                            select r).ToArray()
                };
                var serializer = new JavaScriptSerializer();
                serializer.MaxJsonLength = Int32.MaxValue;
                return Content(serializer.Serialize(json), "application/json");
            }
            return null;
        }

        [HttpPost]
        [MenuAuthorized("1", Order = 1)]
        public ActionResult ExportExcel()
        {
            List<InOutRegion> list = CommonFunctions.JsonStrToObject<List<InOutRegion>>(Request.Form["data"]);
            var sbHtml = new System.Text.StringBuilder();
            sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");
            sbHtml.Append("<tr>");
            var lstTitle = new List<string> { "序号", "车牌号", "SIM卡号","所属单位", "进区时间", "出区时间" };
            foreach (var item in lstTitle)
            {
                sbHtml.AppendFormat("<td style='font-size: 14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);
            }
            sbHtml.Append("</tr>");

            for (int i = 0; i < list.Count; i++)
            {
                sbHtml.Append("<tr>");
                sbHtml.AppendFormat("<td>{0}</td>", i + 1);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mName);
                sbHtml.AppendFormat("<td style='vnd.ms-excel.numberformat:@;'>{0}</td>", list[i].mSim);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mDepart);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mInTime);
                sbHtml.AppendFormat("<td>{0}</td>", list[i].mOutTime);
                sbHtml.Append("</tr>");
            }
            sbHtml.Append("</table>");

            //第一种:使用FileContentResult
            byte[] fileContents = System.Text.Encoding.Default.GetBytes(sbHtml.ToString());
            return File(fileContents, "application/ms-excel", "进出区域明细.xls");

            ////第二种:使用FileStreamResult
            //var fileStream = new MemoryStream(fileContents);
            //return File(fileStream, "application/ms-excel", "fileStream.xls");

            ////第三种:使用FilePathResult
            ////服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.
            //var fileName = Server.MapPath("~/Files/fileName.xls");
            //return File(fileName, "application/ms-excel", "fileName.xls");
            //return null;
        }
    }
}
